import {
	request
} from './request.js';

import store from '../store/index.js';

// 搜索请求:
// 1.购物车搜索(扫码/搜索isbn)
// 2.首页搜索详情
// 此方法只处理关于查找书籍的相关,其余判断跳转在具体页面实现
// 算法:先判断books的本地缓存有无记录,有则直接返回书的详细信息,无则网络请求添加入books本地缓存中


export async function queryBook(isbn) {
	const value = await request({
		header:{
			'Content-type':'application/x-www-form-urlencoded'
		},
		url: "/book/queryBook",
		method: "post",
		data: {
			isbn:isbn
		}
	});
	
	// console.log(value.data.data);

	
	if(value.data.code == 200){
			let res = value.data.data;
			let book = {
				isbn: res.isbn,
				title: res.title,
				price: res.price,
				img: res.img !== "" ? res.img : 'https://ae01.alicdn.com/kf/Hab238867f17c4ea18e02d48a85f786227.jpg',
				author: res.author !== "" ? res.author : '暂无信息',
				publisher: res.publisher !== "" ? res.publisher : '暂无信息',
				pubdate: res.pubDate !== "" ? res.pubDate : '暂无信息',
				binding: res.binding !== "" ? res.binding : '暂无信息',
				gist: res.gist !== "" ? res.gist : '暂无简介'
			};
			return book;
	}else {
		uni.showModal({
			title: '错误',
			content: value.data.msg,
			mask: true,
			showCancel: false
		});
	}

}

export function createBuyOrder(books){
	request({
		url:'/order/generateBuyOrder',
		header:{
			'Content-type':'application/x-www-form-urlencoded'
		},
		method:'post',
		data:{
			
		}
	})
}

export async function handleSearch(e) {
	// console.log(e);
	let resultIndex;
	let books = uni.getStorageSync("history") || [];
	// 如果是books为空,直接请求查找; 否则遍历寻找是否有记录
	if (books.length === 0) {
		const res = await queryBook(e);
		books.push(res);
		resultIndex = 0;
	} else {
		
		// books.forEach(item => {
		// 	if(item.isbn == e){
		// 		let book = {
		// 			...item
		// 		}
		// 		return book;
		// 	}
		// })
		resultIndex = books.findIndex(item=>item.isbn == e)
		if(resultIndex == -1){
			// 如果没有记录就直接请求并加到books中
			const res = await queryBook(e);
			books.push(res);
			resultIndex = books.length - 1;
		}
		
	}

	uni.setStorageSync("history", books);
	return books[resultIndex];



}

//取消订单
export async function cancelOrder(order_id){
	// console.log(order_id);
	return await request({
		method:'post',
		url:'/order/cancelOrder',
		header:{
			'content-type': 'application/x-www-form-urlencoded',
			'token':uni.getStorageSync('token')
		},
		data:{
			order_id:order_id
		}
	})
}

//获取用户所有订单
export async function queryOrdersByUser(){
	const value = await request({
		method:'post',
		url:'/order/queryOrdersByUser',
		header:{
			'content-type': 'application/x-www-form-urlencoded',
			'token':uni.getStorageSync('token')
		}
	});
	// console.log(value);
	
	if(value.data.code == 200){
		return value.data.data;
	}else{
		uni.showModal({
			title: '错误',
			content: value.data.msg,
			mask: true,
			showCancel: false
		});
	}
}


//提交订单
export function submitOrder(buyOrder,rentOrder){
	// let buyOrderId = '';
	// let rentOrderId = '';
	console.log(buyOrder,rentOrder);
	if(!(buyOrder || rentOrder)) {
		uni.showModal({
				title: '错误',
				content: '提交订单不能为空',
				mask: true,
				showCancel: false
			});
			return;
		
	}
	
	if(buyOrder){
		// buyOrder = JSON.stringify(buyOrder);
		request({
			method:'post',
			url:'/order/generateBuyOrder',
			header:{
				'content-type': 'application/json',
				'token':uni.getStorageSync('token'),
			},
			data:buyOrder
				// money:buyOrder.money,
				// order_status:1,
				// pay_time:new Date(),
				// order:buyOrder
				// books:buyOrder.books
			
		}).then((res) => {
			if(res.data.code == 200){
				buyOrderId = res.data.data;
				// console.log(buyOrderId);
			}else {
				uni.showModal({
					title: '错误',
					content: res.data.msg,
					mask: true,
					showCancel: false
				});
				return;
			}
		}).catch((reason) => {
			uni.showModal({
				title: '错误',
				content: reason,
				mask: true,
				showCancel: false
			});
			return;
		});
	}
	
	if (rentOrder){
		request({
			method:'post',
			url:'/order/generateRentOrder',
			header:{
				'content-type': 'application/json',
				'token':uni.getStorageSync('token')
			},
			data:rentOrder
				// money:rentOrder.money,
				// order_status:4,
				// pay_time:new Date(),
				// books:rentOrder.books
				// order:rentOrder
				// books:rentOrder.books
			
		}).then(res => {
			if(res.data.code == 200){
				rentOrderId = res.data.data;
				
			}else{
				uni.showModal({
					title: '错误',
					content: res.data.msg,
					mask: true,
					showCancel: false
				});
				return;
			}
		}).catch(reason => {
			uni.showModal({
				title: '错误',
				content: reason,
				mask: true,
				showCancel: false
			});
			return;
		})
	}
	
	
	
	
	
}

//查询购物车
export function queryCart(cart_type){
	return request({
		url:'/cart/queryCartItems',
		header:{
			'Content-type':'application/x-www-form-urlencoded',
			'token':uni.getStorageSync('token')
		},
		method:'post',
		data:{
			type:cart_type
		}
	})
}

//更新商品项信息
export function updateCartItems(e){
	let url = e.type == 0?'/cart/updateBuyCart':'/cart/updateRentCart';
	console.log(e);
	return request({
		url:url,
		header:{
			'Content-type':'application/json',
			'token':uni.getStorageSync('token')
		},
		method:'post',
		data:e.items
	})
}

//删除商品项
export async function deleteCartItem(isbn,type){
	return await request({
		url:'/cart/deleteCartItem',
		header:{
			'Content-type':'application/x-www-form-urlencoded',
			'token':uni.getStorageSync('token')
		},
		method:'post',
		data:{
			isbn:isbn,
			type:type
		}
	})
}

// 增加请求:
export function handleAddCartItem(items,type) {
	if(type == 0){
		request({
			url: "/cart/addBuyCartItem",
			method: "POST",
			dataType: "json",
			header:{
				'content-type': 'application/json',
				'token':uni.getStorageSync('token'),
			},
			data: [items]
			
		}).then(value => {
			console.log(value);
		}).catch(reason => {
			uni.showModal({
				title: '错误',
				content: reason,
				mask: true,
				showCancel: false
			});
		})
	}else{
		request({
			url: "/cart/addRentCartItem",
			method: "POST",
			dataType: "json",
			header:{
				'content-type': 'application/json',
				'token':uni.getStorageSync('token'),
			},
			data: [items]
			
		}).then(value => {
			console.log(value);
		}).catch(reason => {
			uni.showModal({
				title: '错误',
				content: reason,
				mask: true,
				showCancel: false
			});
		})
	}
	
}

//清空购物车
export function clearItems(){
	request({
		url:'/cart/clearItems',
		method:'POST',
		dataType:'json',
		header:{
			'content-type': 'application/json',
			'token':uni.getStorageSync('token'),
		}
	}).then(res=>{
		if(!res.data.code == 200){
			uni.showModal({
				title: '错误',
				content: res.data.msg,
				mask: true,
				showCancel: false
			});
		}
	}).catch(reason => {
			uni.showModal({
				title: '错误',
				content: reason,
				mask: true,
				showCancel: false
			});
		})
}


//登出
export async function wxLogout(){
	let that = this;
	const value = await request({
		method: 'POST',
		url: '/user/logout',
		header: {
			'content-type': 'application/x-www-form-urlencoded',
			'token':uni.getStorageSync('token')
		}
	});
	// console.log(value);
	if(value.data.code == 200){
		store.commit('logout');
	}else{
		uni.showModal({
			title: '错误',
			content: value.data.msg,
			mask: true,
			showCancel: false
		});
	}
}

// 登录
export function wxLogin(userData) {

	let that = this;
	// if(userData){
	// console.log(userData);
	uni.login({
			provider: 'weixin',
			success: (login_res) => {
				// console.log(login_res.code);
				// uni.getUserInfo({
				// success: (info_res) => {
				request({
					method: 'POST',
					url: '/user/login',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						
					},
					data: {
						code: login_res.code,
						rawData: userData.rawData,
						signature: userData.signature
					}
				}).then(res => {

					if (res.data.code == 200) {
						store.commit('login',{
							userInfo:userData.rawData,
							token: res.data.data
						});
						uni.reLaunch({
							url: '../index/index'
						})
					} else {
						uni.showModal({
							title: '错误',
							content: res.data.msg,
							mask: true,
							showCancel: false
						});
					}
					console.log(res);
				}).catch(reason => {
					uni.showModal({
						title: '错误',
						content: reason,
						mask: true,
						showCancel: false
					});
					console.log(reason);
				})
			},
			fail: (error) => {
				uni.showModal({
					title: '错误',
					content: error,
					mask: true,
					showCancel: false
				});
				console.log(error);
			}
		})
	}
	


